package com.qyhl.webtv.module_circle.circle.moment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.inter.HomeActivityInterface;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.qyhl.webtv.module_circle.circle.home.CircleHomeFragment;
import com.qyhl.webtv.module_circle.utils.itemview.ItemPictureView;
import com.qyhl.webtv.module_circle.utils.itemview.ItemTextView;
import com.qyhl.webtv.module_circle.utils.itemview.ItemVideoView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/1/18.
 * 圈子动态
 */

public class CircleMomentFragment extends BaseFragment implements CircleMomentContract.CircleMomentView, BaseActivity.InputListener {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.editbar)
    EditBar editbar;

    private boolean editbarEnable = true;
    private boolean isVisibleToUser = false;
    private View view;

    private CircleMomentPresenter mPresenter;

    private MultiItemTypeAdapter mAdapter;

    private List<CircleHomeBean> mDataList;

    private String lastId = "0";

    private CircleHomeFragment homeFragment;

    private CircleHomeBean mBean;
    private int postion, uPos;
    private String date, content;

    private LoadingDialog.Builder builder;

    private RefreshHotTopic refreshHotTopic;

    public void setHomeFragment(CircleHomeFragment homeFragment) {
        this.homeFragment = homeFragment;
    }

    public void setRefreshHotTopic(RefreshHotTopic refreshHotTopic) {
        this.refreshHotTopic = refreshHotTopic;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.circle_fragment_circle_moment, null);
    }

    @Override
    protected void create() {
        mPresenter = new CircleMomentPresenter(this);
        BusFactory.getBus().register(this);
        initView();
    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void setListener() {
        setListeners();
        loadData();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    HomeActivityInterface homeActivityInterface;

    public void setHomeActivityInterface(HomeActivityInterface homeActivityInterface) {
        this.homeActivityInterface = homeActivityInterface;
    }

    public static CircleMomentFragment newInstance(CircleHomeFragment fragment, HomeActivityInterface homeActivityInterface) {
        CircleMomentFragment circleMomentFragment = new CircleMomentFragment();
        circleMomentFragment.setHomeFragment(fragment);
        circleMomentFragment.setHomeActivityInterface(homeActivityInterface);
        return circleMomentFragment;
    }


    /**
     * 加载数据
     */
    private void loadData() {
        String userName = CommonUtils.getInstance().getUserName();
        mPresenter.getContent(userName, lastId);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (isVisibleToUser) {

        } else {
            GSYVideoManager.releaseAllVideos();
        }
        if (editbar != null && editbar.getVisibility() == View.VISIBLE) {
            editbar.clearContent();
            editbar.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化界面
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        builder = new LoadingDialog.Builder(getActivity());
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        mDataList = new ArrayList<>();

        editbar.setActivity(getActivity());
        editbar.hideShare(true);
        editbar.hideCollect(true);
        editbar.hideComment(true);
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setEnableLoadMore(true);

        //初始化列表
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.circle_recycleview_divider));
        recyclerView.addItemDecoration(divider);

        mAdapter = new MultiItemTypeAdapter(getContext(), mDataList);
        mAdapter.addItemViewDelegate(new ItemPictureView(getActivity(), true));
        mAdapter.addItemViewDelegate(new ItemTextView(getActivity(), true));
        mAdapter.addItemViewDelegate(new ItemVideoView(getActivity(), true));


        recyclerView.setAdapter(mAdapter);

    }

    /**
     * 设置监听
     */
    private void setListeners() {
        if (homeActivityInterface != null) {
            homeActivityInterface.addInputListener(this);
        }
        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            lastId = "0";
            String userName = CommonUtils.getInstance().getUserName();
            mPresenter.getContent(userName, lastId);
            refreshHotTopic.refresh();
        });

        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                homeFragment.doRefresh();
                lastId = "0";
                String userName = CommonUtils.getInstance().getUserName();
                mPresenter.getContent(userName, lastId);
            }
        });

        //加载
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                String userName = CommonUtils.getInstance().getUserName();
                mPresenter.getContent(userName, lastId);
            }
        });


        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (!mDataList.get(position).isLocal) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mDataList.get(position).getId() + "");
                    RouterManager.router(ARouterPathConstant.CIRCLE_DETAIL, bundle);

                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.CIRCLEDETAIL);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        //文本框
        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void editClick() {
                homeActivityInterface.setTabbarVisibility();
            }

            @Override
            public void onSend() {
                if (editbarEnable) {
                    editbarEnable = false;

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                content = editbar.getContent();
                                String dstUsername;
                                if (StringUtils.isNotEmpty(content)) {
                                    if (uPos == -1) {
                                        dstUsername = "";
                                    } else {
                                        dstUsername = mBean.getPostList().get(uPos).getUser().getUsername();
                                    }
                                    builder.show();
                                    date = DateUtils.getCurrentTime();
                                    mPresenter.sendComment(mBean.getId() + "", content, dstUsername);
                                    editbar.clearContent();
                                } else {
                                    Toasty.normal(getContext(), "评论不能为空！").show();
                                    editbarEnable = true;
                                }
                            } else {
                                Toasty.normal(getContext(), "尚未登录或登录已失效！").show();
                                RouterManager.routerLogin(getContext(), 0);
                                editbarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            editbarEnable = true;
                        }
                    });
                }
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState && editbar.getVisibility() == View.VISIBLE) {
                    editbar.clearContent();
                    editbar.setVisibility(View.GONE);
                }
            }
        });


    }

    /**
     * 设置首页内容
     *
     * @param beanList
     * @param isMore
     */
    @Override
    public void setContent(List<CircleHomeBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~~");
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);

        lastId = beanList.get(beanList.size() - 1).getId() + "";

        if (isMore) {
            mDataList.addAll(beanList);
        } else {
            mDataList.clear();
            if (Hawk.contains("circle_local")) {
                List<CircleHomeBean> localList = Hawk.get("circle_local");
                for (int i = 0; i < localList.size(); i++) {
                    boolean b = false;
                    for (int j = 0; j < beanList.size(); j++) {
                        if (localList.get(i).getId() == beanList.get(j).getId()) {
                            b = true;
                        }
                    }
                    if (!b) {
                        beanList.add(0, localList.get(i));
                    }
                }
                mDataList.addAll(beanList);
            } else {
                mDataList.addAll(beanList);
            }
        }

        mAdapter.notifyDataSetChanged();

    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        loadMask.setReloadButtonText("点击重试~~");
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~~");
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorImage(R.drawable.error_content);
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        loadMask.setReloadButtonText("点击重试~~");
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorImage(R.drawable.empty_content);
    }

    @Override
    public void setLog(String msg) {
        loadMask.setReloadButtonText("点击重试~~");
        refresh.finishRefresh();
        refresh.finishLoadMore();
        Log.i("info", msg);
    }

    @Override
    public void showMessage(String msg) {
        loadMask.setReloadButtonText("点击重试~~");
        refresh.finishRefresh();
        refresh.finishLoadMore();
        Toasty.normal(getContext(), msg).show();
    }

    @Override
    public void commentSuccess(int postId, String msg, int code) {
        Toasty.normal(getContext(), msg).show();
        builder.dismiss();
        //0评论  1回复
        CircleHomeBean.PostList postBean;
        String nickName = CommonUtils.getInstance().getNickName();
        String userName = CommonUtils.getInstance().getUserName();
        String headicon = CommonUtils.getInstance().getUserLogo();
        if (code == 0) {
            postBean = new CircleHomeBean.PostList(date, postId, 1, content, new CircleHomeBean.User(nickName, headicon, userName, false), mBean.getUser());
        } else {
            postBean = new CircleHomeBean.PostList(date, postId, 2, content, new CircleHomeBean.User(nickName, headicon, userName, false), mBean.getPostList().get(uPos).getUser());
        }
        if (mBean.getPostList() != null && mBean.getPostList().size() >= 4) {
            mBean.getPostList().add(0, postBean);
            mBean.getPostList().remove(3);
        } else if (mBean.getPostList() == null) {
            List<CircleHomeBean.PostList> beanList = new ArrayList<>();
            beanList.add(postBean);
            mBean.setPostList(beanList);
        } else {
            mBean.getPostList().add(0, postBean);
        }
        mBean.setPostCount(mBean.getPostCount() + 1);
        mDataList.set(postion, mBean);
        mAdapter.notifyDataSetChanged();
        editbar.clearContent();
        editbar.setVisibility(View.GONE);
        editbarEnable = true;
        String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        if (integralSwitch.equals("1")) {
            getCommentCoin();
        }
    }

    @Override
    public void commentError(String msg) {
        builder.dismiss();
        Toasty.normal(getContext(), msg).show();
        editbarEnable = true;
    }

    @Override
    public void getCoinSuccess(CoinBean coinBean) {
        Toasty.normal(getContext(), "成功评论，获得" + coinBean.getCoin() + "金币！").show();
    }

    @Override
    public void getCoinError(String msg) {
        Log.i("coin_error", msg);
    }

    /**
     * 评论获取金币
     */
    private void getCommentCoin() {

        mPresenter.getCommentCoin();


    }

    /**
     * 评论事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentMessage(Event.CommentEvent event) {
        if (event != null) {
            homeActivityInterface.setTabbarVisibility();
            editbar.setVisibility(View.VISIBLE);
            editbar.changeStateSend(getActivity());
            mBean = event.getBean();
            postion = event.getPostion();
            uPos = event.getuPos();
            if (uPos < 0) {
                editbar.setEditTextHint("评论");
            } else {
                editbar.setEditTextHint("回复:" + mBean.getPostList().get(uPos).getUser().getNickName());
            }
        }
    }


    /**
     * 点赞状态改变事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void praiseMessage(Event.praiseRefreshEvent event) {
        if (event != null) {
            int topicId = event.getTopicId();
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getId() == topicId) {
                    if (event.getType() == 1) {
                        mDataList.get(i).setLove(true);
                        mDataList.get(i).setLoveCount(mDataList.get(i).getLoveCount() + 1);
                    } else {
                        mDataList.get(i).setLove(false);
                        mDataList.get(i).setLoveCount(mDataList.get(i).getLoveCount() - 1);
                    }
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 登录状态改变事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            lastId = "0";
            String userName = CommonUtils.getInstance().getUserName();
            mPresenter.getContent(userName, lastId);
        }
    }

    /**
     * 双击返回顶部事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void backToTop(Event.backToTopEvent event) {
        if (event != null) {
            if (event.getType() == 1) {
                recyclerView.scrollToPosition(0);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.circleRefresh event) {
        if (event != null && mDataList != null) {
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getId() == event.getTopicId()) {
                    mDataList.remove(i);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void circleLocalAdd(Event.circleLocalAdd event) {
        if (event != null) {
            mDataList.add(0, event.getBean());
            mAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
        homeActivityInterface.removeInputListener(this);
    }


    @Override
    public void showkeyboard() {
        if (isVisibleToUser) {
            editbar.getEditText().requestFocus();
        }
    }

    @Override
    public void hideKeyboard() {
        if (isVisibleToUser) {
            editbar.getEditText().clearFocus();
        }
    }

    /**
     * 刷新话题接口
     */
    public interface RefreshHotTopic {
        /**
         * 用于刷新寄主页面
         */
        void refresh();
    }

}

